package com.wuliupai.delivery.wuliupaidelivery.activity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.wuliupai.delivery.wuliupaidelivery.App;
import com.wuliupai.delivery.wuliupaidelivery.R;
import com.wuliupai.delivery.wuliupaidelivery.bean.BaseBean;
import com.wuliupai.delivery.wuliupaidelivery.bean.CancelTaskBean;
import com.wuliupai.delivery.wuliupaidelivery.bean2.qr.QRCodeBean;
import com.wuliupai.delivery.wuliupaidelivery.bean2.task.TaskBean;
import com.wuliupai.delivery.wuliupaidelivery.bean2.user.TaskSourceUserInfoBean;
import com.wuliupai.delivery.wuliupaidelivery.constants.BroadcastChannels;
import com.wuliupai.delivery.wuliupaidelivery.constants.InterfaceNet;
import com.wuliupai.delivery.wuliupaidelivery.constants.PageFlag;
import com.wuliupai.delivery.wuliupaidelivery.constants.Value;
import com.wuliupai.delivery.wuliupaidelivery.net.NetResultOperate;
import com.wuliupai.delivery.wuliupaidelivery.utils.CommonUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.DateUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.ImageLoaderUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.JsonUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.LogUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.MoneyUtil;
import com.wuliupai.delivery.wuliupaidelivery.utils.NumberUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.SelectUtil;
import com.wuliupai.delivery.wuliupaidelivery.utils.SharePreferenceUtil;
import com.wuliupai.delivery.wuliupaidelivery.utils.StringUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.TimeCountDownUtil;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;

import java.lang.reflect.Field;

/**
 * Descriptions：任务详情
 * <p>
 * Author：ChenME
 * Date：2017/11/21
 * Email：ibelieve1210@163.com
 */
@EActivity(R.layout.activity_task_detail)
public class TaskDetailActivity extends AppBaseActivity {

    @Bean(CommonUtils.class)
    CommonUtils commonUtils;
    @Bean(DateUtils.class)
    DateUtils dateUtils;
    @Bean(MoneyUtil.class)
    MoneyUtil moneyUtil;

    // 订单来源
    @ViewById(R.id.rl_sourceOfTask)
    RelativeLayout rl_sourceOfTask;
    @ViewById(R.id.iv_sourcePersonCover)
    ImageView iv_sourcePersonCover;
    @ViewById(R.id.tv_sourcePersonName)
    TextView tv_sourcePersonName;
    @ViewById(R.id.tv_sourcePersonPhone)
    TextView tv_sourcePersonPhone;

    // 任务信息头
    @ViewById(R.id.tv_taskNo)
    TextView tv_taskNo;
    @ViewById(R.id.iBtn_showTaskNoQRCode)
    ImageButton iBtn_showTaskNoQRCode;
    @ViewById(R.id.tv_time)
    TextView tv_time;

    // 出发
    @ViewById(R.id.tv_addressFrom)
    TextView tv_addressFrom;
    @ViewById(R.id.tv_personFrom)
    TextView tv_personFrom;
    @ViewById(R.id.tv_personPhoneFrom)
    TextView tv_personPhoneFrom;

    // 目的
    @ViewById(R.id.tv_addressTo)
    TextView tv_addressTo;
    @ViewById(R.id.tv_personTo)
    TextView tv_personTo;
    @ViewById(R.id.tv_personPhoneTo)
    TextView tv_personPhoneTo;

    // 货物信息
    @ViewById(R.id.tv_orderNo)
    TextView tv_orderNo;
    @ViewById(R.id.tv_goodsName)
    TextView tv_goodsName;
    @ViewById(R.id.tv_goodsWeightVolume)
    TextView tv_goodsWeightVolume;

    // 支付信息
    @ViewById(R.id.iv_dividerAbovePayInfo)
    ImageView iv_dividerAbovePayInfo;
    @ViewById(R.id.rl_payInfo)
    RelativeLayout rl_payInfo;

    @ViewById(R.id.tv_payType)
    TextView tv_payType;
    @ViewById(R.id.tv_payTotal)
    TextView tv_payTotal;
    @ViewById(R.id.tv_payAlready)
    TextView tv_payAlready;
    @ViewById(R.id.tv_payLeft)
    TextView tv_payLeft;

    // 按钮相关
    @ViewById(R.id.rl_bottomBtn)
    RelativeLayout rl_bottomBtn;// 底部的按钮
    @ViewById(R.id.tv_rightBtn2)
    TextView tv_rightBtn2;// 右数第2个按钮
    @ViewById(R.id.tv_rightBtn1)
    TextView tv_rightBtn1;// 右数第1个按钮
    @ViewById(R.id.tv_rightBtn0)
    TextView tv_rightBtn0;// 右数第0个按钮

    @Extra("taskId")
    String taskId = "";//任务的ID
    @Extra("taskResourceUserId")
    String taskResourceUserId;// 任务来源的UserId
    @Extra("whichPage")
    int whichPage = PageFlag.Page_TaskRecordList;

    private TaskDetailActivity _activity;

    private static final int BtnTag_ChangeTask = 1, // 交换任务
            BtnTag_AcceptTask = 2, // 接受任务（交换任务时）
            BtnTag_SignFor = 3, // 签收
            BtnTag_Packing = 4; // 揽收

    private String phoneSource = "", // 任务来源的电话
            phonePersonFrom = "", // 起点电话
            phonePersonTo = ""; // 终点电话

    private String orderId = "", // 订单ID，用于查看订单详情使用
            orderCode = "", // 用于揽收货物使用
            taskNo = ""; //任务的编号

    private String taskType = ""; // 任务类型

    private boolean isAlreadyTaking = false;// 是否已经揽收

    private String cancelTaskReasonId = "-1";//取消任务的原因ID
    private final String CancelTaskReasonId_CarErr = "label1";//车辆故障
    private final String CancelTaskReasonId_CarFull = "label2";//车已装满
    private final String CancelTaskReasonId_CarLimit = "label3";//车辆限行
    private final String CancelTaskReasonId_Other = "label0";//其他
    private MenuItem miCancelTask = null; // 取消任务的菜单

    @AfterViews
    void onPageStart() {
        _activity = this;

        int titleRes = R.string.string_taskDetail_title;
        loadTaskDetail();
        if (PageFlag.Page_ScanQrCode == whichPage) {
            loadTaskSourceData();
            titleRes = R.string.string_taskDetail_title2;
        }

        setTitle(_activity, titleRes, R.drawable.comm_press_return_selector,
                true, new OnNavigationBtnClickListener() {
                    @Override
                    public void navigationClick() {
                        finish();
                        animUtils.leftOutAnimation(_activity);
                    }

                    @Override
                    public void menuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.menuItem1:
                                showCancelTaskReasonDialog();
                                break;
                        }
                    }
                });
    }

    /**
     * 加载任务来源的用户信息
     */
    private void loadTaskSourceData() {
        TaskSourceUserInfoBean taskSourceUserInfoBean = new TaskSourceUserInfoBean(taskResourceUserId);
        String jsonRequest = JsonUtils.createJsonString(taskSourceUserInfoBean);
        try {
            String aesRequest = JsonUtils.aes(jsonRequest);
            callNet(this, InterfaceNet.Net_GetTaskSourceByUserId, aesRequest, new NetResultOperate() {
                @Override
                public void onSuccess(String content) {
                    if (!StringUtils.isEmpty(content)) {
                        TaskSourceUserInfoBean result = (TaskSourceUserInfoBean) JsonUtils.parseJsonString(content, TaskSourceUserInfoBean.class);
                        if (null != result) {
                            phoneSource = result.getLoginName();
                            showTaskSourceView(result.getIdName(), result.getHeadUrl());
                        }
                    }
                }

                @Override
                public void onDataEmpty(String content) {
                }

                @Override
                public void onDataEnd(String content) {
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 加载任务详情的数据
     */
    private void loadTaskDetail() {

        TaskBean taskBean = new TaskBean(taskId);
        String jsonRequest = JsonUtils.createJsonString(taskBean);
        try {
            String aesRequest = JsonUtils.aes(jsonRequest);
            callNet(this, InterfaceNet.Net_GetTaskDetail, aesRequest, new NetResultOperate() {
                @Override
                public void onSuccess(String content) {
                    if (!StringUtils.isEmpty(content)) {
                        TaskBean result = (TaskBean) JsonUtils.parseJsonString(content, TaskBean.class);
                        if (null != result) {
                            bindData(result);
                        }
                    }
                }

                @Override
                public void onDataEmpty(String content) {
                }

                @Override
                public void onDataEnd(String content) {
                    App.toast(R.string.strings_common_dateEnd);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 绑定数据
     *
     * @param bean
     */
    private void bindData(TaskBean bean) {

        orderId = bean.getOrderId();
        taskNo = bean.getMissionCode();
        taskType = bean.getCollectGoods();
        isAlreadyTaking = "2".equals(bean.getNowUserType());// 为2表示已经揽收

        if (PageFlag.Page_ScanQrCode != whichPage) {
            String nameSource = bean.getAssignName();
            phoneSource = bean.getAssignPhone();
            if (!StringUtils.isEmpty(nameSource)) {
                showTaskSourceView(nameSource, bean.getAssignHeadUrl());
            } else {
                rl_sourceOfTask.setVisibility(View.GONE);
            }
        }

        tv_taskNo.setText(StringUtils.splitString(taskNo, " ", StringUtils.SPLIT_TYPE_2));
        tv_time.setText(dateUtils.formatData(bean.getSubmitTime(), "yyyy/M/d HH:mm"));

        tv_addressFrom.setText(bean.getStartAddress());
        tv_personFrom.setText(bean.getStartContactName());
        phonePersonFrom = bean.getStartContactPhone();
        tv_personPhoneFrom.setText(phonePersonFrom);

        tv_addressTo.setText(bean.getEndAddress());
        tv_personTo.setText(bean.getEndContactName());
        phonePersonTo = bean.getEndContactPhone();
        tv_personPhoneTo.setText(phonePersonTo);

        orderCode = bean.getOrderCode();
        tv_orderNo.setText(StringUtils.splitString(orderCode, " ", StringUtils.SPLIT_TYPE_2));
        tv_goodsName.setText(bean.getGoodsName());
        tv_goodsWeightVolume.setText(StringUtils.formatWeight(bean.getGoodsWeight()) + "/" + StringUtils.formatVolume(bean.getGoodsVolume()));

        if (PageFlag.Page_TaskRecordList != whichPage) { // 非订单记录页面进入

            rl_bottomBtn.setVisibility(View.VISIBLE);

            int needToPayMoney = NumberUtils.formatStringToInt(bean.getDealPrice()) - NumberUtils.formatStringToInt(bean.getActualMoney());
            if (needToPayMoney > 0) {
                iv_dividerAbovePayInfo.setVisibility(View.VISIBLE);
                rl_payInfo.setVisibility(View.VISIBLE);
                tv_payTotal.setText("￥" + moneyUtil.format2Yuan(bean.getDealPrice()));
                tv_payAlready.setText(" - ￥" + moneyUtil.format2Yuan(bean.getActualMoney()));
                tv_payLeft.setText(" = ￥" + moneyUtil.format2Yuan(needToPayMoney));
                tv_payType.setText(SelectUtil.initPayWay().get(bean.getPayType()));
            } else {
                iv_dividerAbovePayInfo.setVisibility(View.GONE);
                rl_payInfo.setVisibility(View.GONE);
            }

            if (PageFlag.Page_ScanQrCode == whichPage) { // 扫码界面进入
                tv_rightBtn1.setVisibility(View.VISIBLE);
                tv_rightBtn1.setTag(BtnTag_AcceptTask);
                tv_rightBtn1.setText("接收任务");

            } else { // 当前任务进入

                iBtn_showTaskNoQRCode.setVisibility(View.VISIBLE);

                if (Value.TaskSource_Collect.equals(taskType)) { // 收货
                    // taskType ==1

                    tv_rightBtn2.setVisibility(View.VISIBLE);
                    tv_rightBtn2.setText("查看订单");

                    tv_rightBtn1.setVisibility(View.VISIBLE);
                    tv_rightBtn1.setTag(BtnTag_ChangeTask);
                    tv_rightBtn1.setText("交换任务");

                    if (!isAlreadyTaking) { // 还没有揽收
                        tv_rightBtn0.setVisibility(View.VISIBLE);
                        tv_rightBtn0.setTag(BtnTag_Packing);
                        tv_rightBtn0.setText("揽 收");
                    }
                }

                if (isAlreadyTaking) { // 已经揽收
                    if ("1".equals(bean.getIsConfirm())) { // 在车上
                        tv_rightBtn0.setVisibility(View.VISIBLE);
                        tv_rightBtn0.setTag(BtnTag_SignFor);
                        tv_rightBtn0.setText("确认签收");
                    } else {
                        tv_rightBtn0.setVisibility(View.GONE);
//                    rl_bottomBtn.setVisibility(View.GONE);
                    }
                }
            }
        }
    }

    /**
     * 隐藏所有的按钮
     */
    private void hindAllBtn(){
        rl_bottomBtn.setVisibility(View.GONE);
        tv_rightBtn0.setVisibility(View.GONE);
        tv_rightBtn1.setVisibility(View.GONE);
        tv_rightBtn2.setVisibility(View.GONE);
    }
    /**
     * 当网络请求成功
     */
    private void whenNetworkSuccess() {
        hindAllBtn();
        loadTaskDetail();
        if (PageFlag.Page_ScanQrCode == whichPage) {
            loadTaskSourceData();
        }
    }

    /**
     * 显示任务来源View
     *
     * @param nameSource
     * @param coverSource
     */
    private void showTaskSourceView(String nameSource, String coverSource) {
        rl_sourceOfTask.setVisibility(View.VISIBLE);
        ImageLoader.getInstance().displayImage(coverSource, iv_sourcePersonCover, ImageLoaderUtils.loadImageWithCustomRoundCorner(_activity, commonUtils.dp2px(getResources().getDimension(R.dimen.size_taskDetail_sourcePersonCover))));
        tv_sourcePersonName.setText(nameSource);
        tv_sourcePersonPhone.setText(phoneSource);
    }

    /**
     * 显示交换货物的提示对话框
     */
    private void showChangTaskTipsDialog() {

        if (SharePreferenceUtil.getShowChangeTaskTipsDialogStatus(_activity)) {

            showCommonDialog("温馨提示", "继续", "不再提醒", true, new OnCommonDialogBtnClickListener() {
                @Override
                public void setContentText(TextView tv_content) {
                    tv_content.setText(Html.fromHtml(getString(R.string.string_taskChangeTipDialog_content)));
                }

                @Override
                public void onLeftBtnClick(Dialog dialog) {
                    changeTask();
                }

                @Override
                public void onRightBtnClick(Dialog dialog) {
                    SharePreferenceUtil.saveShowChangeTaskTipsDialogStatus(_activity, false);
                    changeTask();
                }
            });
        } else {
            changeTask();
        }
    }

    /**
     * 显示确认签收的对话框
     */
    private void showSignForTipsDialog() {
        showCommonDialog("提示", "确定", "取消", true, new OnCommonDialogBtnClickListener() {
            @Override
            public void setContentText(TextView tv_content) {
                tv_content.setText("您确认要签收该货物吗？");
            }

            @Override
            public void onLeftBtnClick(Dialog dialog) {
                netSignFor("", dialog);
            }

            @Override
            public void onRightBtnClick(Dialog dialog) {
            }
        });
    }

    /**
     * 显示签收时输入验证码的Dialog
     */
//    private void showInputVerificationCodeDialog() {
//        Dialog view = new Dialog(this, R.style.DialogFullWindowStyle);// 创建自定义样式dialog
//
//        view.setCancelable(false);
//        view.setContentView(R.layout.dialog_input_verification_code);// 设置布局
//
//        TextView tv_tips = (TextView) view.findViewById(R.id.tv_tips);
//        TextView tv_leftBtn = (TextView) view.findViewById(R.id.tv_leftBtn);
//        Button btn_rightBtn = (Button) view.findViewById(R.id.btn_rightBtn);
//        EditText et_verificationCode = (EditText) view.findViewById(R.id.et_verificationCode);
//        et_verificationCode.requestFocus();
//
//        tv_tips.setText(Html.fromHtml(getString(R.string.string_signForTipDialog_verificationTips)));
//
//        tv_leftBtn.setOnClickListener(v -> {
//            String verificationCode = et_verificationCode.getText().toString().trim();
//            if (verificationCode.length() <= 0) {
//                App.toast("请输入验证码！");
//                return;
//            }
//            tv_rightBtn0.setEnabled(false);
//            netSignFor(verificationCode, view);
//        });
//
//        btn_rightBtn.setOnClickListener(v -> netGetVerification(btn_rightBtn));
//
//        view.findViewById(R.id.ivBtn_closeDialog).setOnClickListener(v -> view.dismiss());
//        view.show();
//    }

    /**
     * 获取验证码
     *
     * @param btn
     */
//    private void netGetVerification(Button btn) {
//        TimeCountDownUtil countDownUtil = new TimeCountDownUtil(_activity, 30 * 1000, 1000, btn, R.string.string_signForTipDialog_reGetVerificationBtn, true);
//        countDownUtil.start();
//
//        TaskBean taskBean = new TaskBean();
//        taskBean.setMissionCode(taskNo);
//        taskBean.setOrderCode(orderCode);
//        taskBean.setType("0");
//        String jsonRequest = JsonUtils.createJsonString(taskBean);
//        try {
//            String aesRequest = JsonUtils.aes(jsonRequest);
//            callNet(this, InterfaceNet.Net_TaskGetValidationCode, aesRequest, new NetResultOperate() {
//                @Override
//                public void onSuccess(String content) {
//                    App.toast("验证码已发送至客户手机上!");
//                }
//
//                @Override
//                public void onDataEmpty(String content) {
//                }
//
//                @Override
//                public void onDataEnd(String content) {
//                }
//
//            });
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    /**
     * 签收网络请求
     */
    private void netSignFor(String verificationCode, Dialog dialog) {
        TaskBean taskBean = new TaskBean(taskId, verificationCode);
        taskBean.setMissionCode(taskNo);
        String jsonRequest = JsonUtils.createJsonString(taskBean);
        try {
            String aesRequest = JsonUtils.aes(jsonRequest);
            callNet(this, InterfaceNet.Net_SingForOrder, aesRequest, new NetResultOperate() {
                @Override
                public void onSuccess(String content) {
//                    tv_rightBtn0.setText("签收成功");
                    App.toast("签收成功！");
                    whenNetworkSuccess();
                    dialog.dismiss();

                    LocalBroadcastManager.getInstance(_activity).sendBroadcast(new Intent(BroadcastChannels.Channel_SignForSuccess));
                }

                @Override
                public void onDataEmpty(String content) {
                    setRightBtn0ToReSignFor("签收失败！", "重新签收");
                }

                @Override
                public void onDataEnd(String content) {
                    setRightBtn0ToReSignFor("签收失败！", "重新签收");
                }

                @Override
                public void onErr(String errorCode, String errorMsg, Context mContext) {
                    super.onErr(errorCode, errorMsg, mContext);
                    setRightBtn0ToReSignFor(errorMsg, "重新签收");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置右边第1个按钮为签收失败的状态
     *
     * @param toast
     */
    private void setRightBtn1ToReSignFor(String toast, String btnText) {
        App.toast(toast);
        tv_rightBtn1.setEnabled(true);
        tv_rightBtn1.setText(btnText);
    }

    /**
     * 设置右边第1个按钮为签收失败的状态
     *
     * @param toast
     */
    private void setRightBtn0ToReSignFor(String toast, String btnText) {
        App.toast(toast);
        tv_rightBtn0.setEnabled(true);
        tv_rightBtn0.setText(btnText);
    }

    /**
     * 拨打任务来源的电话
     */
    @Click(R.id.tv_sourcePersonPhone)
    void onSourcePersonPhone() {
        if (!StringUtils.isEmpty(phoneSource)) {
            callPhone(phoneSource);
        }
    }


    /**
     * 交换任务
     */
    private void changeTask() {
        try {
            QRCodeBean qrCodeBean = new QRCodeBean(QRCodeBean.QRCodeType_TaskChang, new BaseBean().getUserId(), taskId);
            String strQRCode = JsonUtils.createJsonString(qrCodeBean);
            String aesQRCode = JsonUtils.aes(strQRCode);
            showQRCodeDialog(_activity, aesQRCode, getString(R.string.string_taskChangeTipDialog_tips1), getString(R.string.string_taskChangeTipDialog_tips2), new OnQRCodeClickListener() {
                @Override
                public void onQRCodeClick(Dialog dialog) {
                }

                @Override
                public void onQRCodeLongClick(Dialog dialog) {
                    ClipboardManager mClipboardManager = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
                    mClipboardManager.setText(aesQRCode);
                    App.toast(R.string.string_taskChangeTipDialog_tipsToast);
                    dialog.dismiss();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            App.toast(R.string.string_taskChangeTipDialog_tipsErrQRCode);
        }
    }

    /**
     * 接受任务
     */
    private void acceptTask() {
        tv_rightBtn1.setEnabled(false);

        TaskBean taskBean = new TaskBean(taskId);
        String jsonRequest = JsonUtils.createJsonString(taskBean);
        try {
            String aesRequest = JsonUtils.aes(jsonRequest);
            callNet(this, InterfaceNet.Net_AcceptTaskWhenChangeTask, aesRequest, new NetResultOperate() {
                @Override
                public void onSuccess(String content) {
//                    tv_rightBtn1.setText("接收成功");
                    App.toast("任务接收成功！");
                    whenNetworkSuccess();
                    LocalBroadcastManager.getInstance(_activity).sendBroadcast(new Intent(BroadcastChannels.Channel_AcceptTaskSuccessWhenChangeTask));
                    finish();
                }

                @Override
                public void onDataEmpty(String content) {
                    setRightBtn1ToReSignFor("接收失败！", "重新接收");
                }

                @Override
                public void onDataEnd(String content) {
                    setRightBtn1ToReSignFor("接收失败！", "重新接收");
                }

                @Override
                public void onErr(String errorCode, String errorMsg, Context mContext) {
                    super.onErr(errorCode, errorMsg, mContext);
                    setRightBtn1ToReSignFor(errorMsg, "重新接收");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 揽收货物
     *
     * @param isOpenOrderDetailWhenTakingSuccess 完成揽收后是否打开订单详情
     */
    private void toTakingPackage(boolean isOpenOrderDetailWhenTakingSuccess) {

        tv_rightBtn0.setEnabled(false);

        TaskBean taskBean = new TaskBean();
        taskBean.setOrderCode(orderCode);
        taskBean.setMissionCode(taskNo);
        String jsonRequest = JsonUtils.createJsonString(taskBean);
        try {
            String aesRequest = JsonUtils.aes(jsonRequest);
            callNet(this, InterfaceNet.Net_TakingPackage, aesRequest, new NetResultOperate() {
                @Override
                public void onSuccess(String content) {
//                    tv_rightBtn0.setVisibility(View.GONE);
                    isAlreadyTaking = true;
                    App.toast("货物揽收成功！");
                    whenNetworkSuccess();
                    if (isOpenOrderDetailWhenTakingSuccess) {
                        OrderDetailActivity_.intent(_activity).orderId(orderId).start();
                        animUtils.leftInAnimation(_activity);
                    }
                }

                @Override
                public void onDataEmpty(String content) {
                    tv_rightBtn0.setEnabled(true);
                    App.toast("货物揽收失败！");
                }

                @Override
                public void onDataEnd(String content) {
                    tv_rightBtn0.setEnabled(true);
                    App.toast("货物揽收失败！");
                }

                @Override
                public void onErr(String errorCode, String errorMsg, Context mContext) {
                    super.onErr(errorCode, errorMsg, mContext);
                    tv_rightBtn0.setEnabled(true);
                    App.toast("货物揽收失败！");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 右数第2个按钮
     * 订单详情
     */
    @Click(R.id.tv_rightBtn2)
    void onRightBtn2() {
        if (isAlreadyTaking) { // 已经揽收
            OrderDetailActivity_.intent(_activity).orderId(orderId).start();
            animUtils.leftInAnimation(_activity);
        } else { // 未揽收
            showCommonDialog("提示", "揽收", "取消", true, new OnCommonDialogBtnClickListener() {
                @Override
                public void setContentText(TextView tv_content) {
                    tv_content.setText("抱歉！您只有在揽收完货物之后，才有权利对订单进行操作！");
                }

                @Override
                public void onLeftBtnClick(Dialog dialog) {
                    toTakingPackage(true);
                }

                @Override
                public void onRightBtnClick(Dialog dialog) {

                }
            });
        }
    }

    /**
     * 右数第1个按钮
     * 接受任务、交换任务
     */
    @Click(R.id.tv_rightBtn1)
    void onRightBtn1(View view) {
        int tag = (int) view.getTag();
        switch (tag) {
            case BtnTag_AcceptTask: // 接受任务
                acceptTask();
                break;
            case BtnTag_ChangeTask: // 交换任务
                showChangTaskTipsDialog();
                break;
            case BtnTag_SignFor: // 签收
//                showInputVerificationCodeDialog();
                showSignForTipsDialog();

                break;
        }
    }

    /**
     * 右数第0个按钮
     * 揽收、签收
     */
    @Click(R.id.tv_rightBtn0)
    void onRightBtn0(View view) {
        int tag = (int) view.getTag();
        switch (tag) {
            case BtnTag_Packing: // 揽收
                toTakingPackage(false);
                break;
            case BtnTag_SignFor: // 签收
//                showInputVerificationCodeDialog();
                showSignForTipsDialog();
                break;
        }

    }

    /**
     * 展示任务编号的二维码
     */
    @Click(R.id.iBtn_showTaskNoQRCode)
    void onShowTaskNoQRCode() {
        if (StringUtils.isEmpty(taskNo)) {
            App.toast("未获取到任务编号，请刷新后再尝试！");
            return;
        }

        if (isAlreadyTaking || Value.TaskSource_NotCollect.equals(taskType)) { // 已经揽收
            try {
                QRCodeBean qrCodeBean = new QRCodeBean();
                qrCodeBean.setTaskNo(taskNo);
                qrCodeBean.setOrderCode(orderCode);
                qrCodeBean.setType(QRCodeBean.QRCodeType_Scan2Storage);
                String strQRCode = JsonUtils.createJsonString(qrCodeBean);
                showQRCodeDialog(_activity, strQRCode, "请库管扫描此二维码入库", "", null);
            } catch (Exception e) {
                e.printStackTrace();
                App.toast(R.string.string_taskChangeTipDialog_tipsErrQRCode);
            }
        } else {
            App.toast("请点击揽收后，才能进行入库操作！");
        }

    }

/** ***********************************************************  取消任务 start  *********************************************************** */

    /**
     * 设置title右侧按键样式
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        miCancelTask = menu.findItem(R.id.menuItem1);
        miCancelTask.setVisible(false).setTitle(R.string.string_orderDetail_cancelTask_title);
        menu.findItem(R.id.menuItem2).setVisible(false);
//        return true;
        return false; // 暂时关闭取消任务的逻辑
    }

    /**
     * 提交取消任务的原因
     *
     * @param et_reasonReplenish
     */
    private void commitReason(EditText et_reasonReplenish, DialogInterface dialog) {
        if ("-1".equals(cancelTaskReasonId)) {
            App.toast("请选择取消任务原因！");
            return;
        }

        CancelTaskBean requestBean = new CancelTaskBean(taskId, cancelTaskReasonId);
        if (CancelTaskReasonId_Other.equals(cancelTaskReasonId)) {
            String reasonReplenish = et_reasonReplenish.getText().toString().trim();
            if (StringUtils.isEmpty(reasonReplenish)) {
                App.toast("请填写原因！");
                return;
            }
            requestBean.setConfirmRemarks(reasonReplenish);
        }
        cancelTaskReasonId = "-1";
        dismissDialog(dialog);

        String requestJson = JsonUtils.createJsonString(requestBean);
        try {
            String requestAes = JsonUtils.aes(requestJson);
            callNet(this, InterfaceNet.Net_CommitCancelTaskReason, requestAes, new NetResultOperate() {
                @Override
                public void onSuccess(String content) {
                    App.toast("提交成功！");
                    loadTaskDetail();
                }

                @Override
                public void onDataEmpty(String content) {
                }

                @Override
                public void onDataEnd(String content) {
                }

                @Override
                public void onErr(String errorCode, String errorMsg, Context mContext) {
                    super.onErr(errorCode, errorMsg, mContext);

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭对话框
     */
    private void dismissDialog(DialogInterface dialog) {
        try {
            Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
            field.setAccessible(true);
            field.set(dialog, true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        dialog.dismiss();
    }

    /**
     * 显示选择取消任务的对话框
     */
    private void showCancelTaskReasonDialog() {
        LayoutInflater inflater = getLayoutInflater();
        View view = inflater.inflate(R.layout.dialog_cancel_task, null);

        TextView tv_title = (TextView) view.findViewById(R.id.tv_title);
        tv_title.setText(getString(R.string.string_orderDetail_cancelTask_dialogTitle));

        RadioButton rb_reason0 = (RadioButton) view.findViewById(R.id.rb_reason0);
        RadioButton rb_reason1 = (RadioButton) view.findViewById(R.id.rb_reason1);
        RadioButton rb_reason2 = (RadioButton) view.findViewById(R.id.rb_reason2);
        RadioButton rb_reason3 = (RadioButton) view.findViewById(R.id.rb_reason3);
        EditText et_reasonReplenish = (EditText) view.findViewById(R.id.et_reasonReplenish);
        ((RadioGroup) view.findViewById(R.id.rg_cancelTaskReason)).setOnCheckedChangeListener((group, checkedId) -> {
            if (checkedId == rb_reason0.getId()) {
                cancelTaskReasonId = CancelTaskReasonId_CarErr;
                et_reasonReplenish.setVisibility(View.GONE);
            } else if (checkedId == rb_reason1.getId()) {
                cancelTaskReasonId = CancelTaskReasonId_CarFull;
                et_reasonReplenish.setVisibility(View.GONE);
            } else if (checkedId == rb_reason2.getId()) {
                cancelTaskReasonId = CancelTaskReasonId_CarLimit;
                et_reasonReplenish.setVisibility(View.GONE);
            } else if (checkedId == rb_reason3.getId()) {
                cancelTaskReasonId = CancelTaskReasonId_Other;
                et_reasonReplenish.setVisibility(View.VISIBLE);
            }
        });
        new AlertDialog.Builder(this)
                .setView(view)
                .setCancelable(false)
                .setPositiveButton(R.string.string_commonConfirmBtn,
                        (dialog1, which) -> {
                            preventDismissDialog(dialog1);
                            commitReason(et_reasonReplenish, dialog1);
                        }

                )
                .setNegativeButton(R.string.string_commonCancelBtn,
                        (dialog12, which) -> {
                            dismissDialog(dialog12);
                            cancelTaskReasonId = "-1";
                        })
                .show();
    }

    /**
     * 通过反射 阻止关闭对话框
     */
    private void preventDismissDialog(DialogInterface dialog) {
        try {
            Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
            field.setAccessible(true);
            //设置mShowing值，欺骗android系统
            field.set(dialog, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
/** ***********************************************************  取消任务 end  *********************************************************** */
}
